#include "FindDevicesMsg.hpp"
#include "../Log.hpp"
#include "../ExceptionUtil.hpp"
#include "../KieperException.hpp"
#include "../NetUtil.hpp"

#include <algorithm>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

namespace kieper {
    using std::copy;

    FindDevicesMsg::FindDevicesMsg(const char* host, unsigned int port) : 
        Message(new Packet(sizeof(in_addr) + 2, Packet::TYPE_CONTROL, Packet::DELIVERY_ASYNC,
        Packet::SCOPE_GLOBAL, Packet::DIRECTION_REQUEST, 0)) {
        getPacket().setPacketId(0);
        getPacket().setDeviceId(0);
        in_addr hostAddr;
        
        LOG_TRACE("host = %s", host);
        if (inet_aton(host, &hostAddr) == 0) {
            THROW(KieperException, "Invalid host address");
        }

        char* payload = getPacket().getPayload();
        netutil::setAsNbo16(payload, 0, port);
        
        char* hostAddrChrPtr = reinterpret_cast<char*> (&hostAddr);
        
        //host address is already in network byte order, no need to convert
        copy(hostAddrChrPtr, hostAddrChrPtr + sizeof(in_addr_t), payload + 2);

    }
    
    FindDevicesMsg::~FindDevicesMsg() {}
}
